package com.duleme.servlet;

import com.google.gson.Gson;
import com.duleme.dao.UserDao;
import com.duleme.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/data/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        String id = req.getParameter("id");
        String type = req.getParameter("type");

        Gson gson = new Gson();
        UserDao userDao = new UserDao();

        //参数为all或single
        if (type.equals("all") || type.equals("")) {
            System.out.println("mode:all");
            List<User> users = userDao.findAllUsers();
            String json = gson.toJson(users);
            resp.getWriter().print(json);
        } else if (type.equals("single")) {
            if (id!= null) {
                System.out.println("mode:single");
                int realid = Integer.parseInt(id);
                User user = userDao.findById(realid);
                String json = gson.toJson(user);
                resp.getWriter().print(json);
            }
        } else {
            resp.getWriter().print("{\"info\":\"访问数据错误\"}");
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        doPost(req,resp);
    }
}
